package com.miaosha.ms_03.validate;

import com.miaosha.ms_03.util.ValidUtil;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Description //手机号码校验
 * @Author Administrator
 * @DATE 2020/9/16 23:05
 **/
public class MobileValidator implements ConstraintValidator<IsMobile, String> {

    private boolean required = false;

    //初始化
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    //校验
    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (required) {
            return ValidUtil.isMobile(value);
        } else {
            // 可以为空，并且为空
            if (StringUtils.isEmpty(value)) {
                return true;
            } else {
                //可以为空 但是不为空，所以需要校验
                return ValidUtil.isMobile(value);
            }
        }
    }
}
